const multer = require('@koa/multer');
const fs = require('fs-extra');
const path = require('path');
const config = require('../config');
const { validatePath, safePath, sanitizeFilename } = require('../utils');

// 配置multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 临时上传到基础目录，后续在控制器中处理路径
    fs.ensureDirSync(config.storage.path);
    cb(null, config.storage.path);
  },
  filename: function (req, file, cb) {
    // 临时文件名，后续会重命名
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2);
    cb(null, `temp_${timestamp}_${random}`);
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: config.storage.maxFileSize
  }
});

class UploadController {
  // 获取multer中间件
  static getUploadMiddleware() {
    return upload.array('files');
  }

  // 处理文件上传
  static async uploadFiles(ctx) {
    try {
      const targetPath = ctx.query.path || '';
      
      // 验证路径安全性
      if (!validatePath(targetPath)) {
        ctx.throw(400, '非法路径');
      }
      
      // 安全路径构建
      const { path: finalDirectory, safe } = safePath(config.storage.path, targetPath);
      if (!safe) {
        ctx.throw(400, '无效的路径');
      }
      
      const uploadedFiles = [];
      
      for (const file of ctx.request.files) {
        const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
        const currentFilePath = file.path;
        
        // 清理文件名，防止路径遍历攻击
        const safeFilename = sanitizeFilename(originalName);
        
        // 确保目标目录存在
        fs.ensureDirSync(finalDirectory);
        
        // 计算最终文件路径
        const finalFilePath = path.join(finalDirectory, safeFilename);
        
        // 移动文件到最终位置
        await fs.move(currentFilePath, finalFilePath);
        
        uploadedFiles.push({
          name: safeFilename,
          originalName: originalName,
          path: finalFilePath,
          size: file.size,
          mimeType: file.mimetype,
          relativePath: targetPath ? path.join(targetPath, safeFilename).replace(/\\/g, '/') : safeFilename
        });
      }
      
      ctx.body = {
        success: true,
        message: `成功上传 ${uploadedFiles.length} 个文件`,
        data: uploadedFiles
      };
    } catch (err) {
      // 清理已上传的临时文件
      if (ctx.request.files) {
        for (const file of ctx.request.files) {
          try {
            await fs.remove(file.path);
          } catch (cleanupErr) {
            console.error('清理临时文件失败:', cleanupErr);
          }
        }
      }
      ctx.throw(500, `文件上传失败: ${err.message}`);
    }
  }
}

module.exports = UploadController; 